package com.yingli.component.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.yingli.component.R;

public class BroadcastActivity extends AppCompatActivity {

    private Button btnSend, btnSendOrder, btnSendSticky;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);
        btnSend = findViewById(R.id.btn_send);
        btnSendOrder = findViewById(R.id.btn_send_order);
        btnSendSticky = findViewById(R.id.btn_send_sticky);
        btnSend.setOnClickListener(v -> {
//            Intent intent = new Intent(this,DemoBroadcast.class);
//            sendBroadcast(intent);
            Intent intent = new Intent("com.demo.receiver");
            intent.putExtra("data", "defaultBroadcast");
            sendBroadcast(intent);
        });
        btnSendOrder.setOnClickListener(t -> {
            Intent intent = new Intent("com.demo.receiver1");
            intent.putExtra("data", "orderBroadcast");
            sendBroadcast(intent);
//            sendOrderedBroadcast();
        });
        btnSendSticky.setOnClickListener(v -> {
//            sendStickyBroadcast();
        });
        IntentFilter intentFilter = new IntentFilter("com.demo.receiver");
        registerReceiver(new DynamicReceiver(), intentFilter);
    }

    class DynamicReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String data = intent.getStringExtra("data");
            if (intent.getAction().equals("com.demo.receiver")) {
                Log.i("dynamicReceiver", "动态Receiver已收到消息" + data);
            }
        }
    }
}
